package com.xuzhiguang.lightnat.common.message;


import com.xuzhiguang.lightnat.common.constant.NatMessageConstants;
import com.xuzhiguang.lightnat.common.serializer.SerializerTypeEnum;
import com.xuzhiguang.lightnat.common.util.IdUtil;
import lombok.Data;

@Data
public class NatMessage {

    private NatMessageHeader header;

    private Object body;

    public NatMessage(Object body) {
        this.body = body;
        this.header = getDefaultHeader();
    }

    public NatMessage(Object body, byte serializerType) {
        this.body = body;
        this.header = this.getDefaultHeader();
        this.header.setSerializerType(serializerType);
    }

    public NatMessage(Object body, long requestId) {
        this.body = body;
        this.header = getDefaultHeader();
        this.header.setRequestId(requestId);
    }

    public NatMessage() {
    }

    private NatMessageHeader getDefaultHeader() {
        NatMessageTypeEnum messageType = NatMessageTypeEnum.findByCls(this.body.getClass());
        if (messageType == null) {
            throw new IllegalArgumentException("messageType is illegal");
        }

        NatMessageHeader header = new NatMessageHeader();
        header.setMagic(NatMessageConstants.MAGIC);
        header.setVersion(NatMessageConstants.VERSION);
        header.setRequestId(IdUtil.nextId());
        header.setSerializerType(SerializerTypeEnum.GSON.getType());
        header.setMessageType(messageType.getType());

        return header;
    }
}
